package com.meixiang.fragment.fund;


import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.ViewCompat;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.reflect.TypeToken;
import com.lzy.okhttputils.model.HttpParams;
import com.meixiang.R;
import com.meixiang.activity.WebviewActivity;
import com.meixiang.activity.account.myfund.MyFundActivity;
import com.meixiang.adapter.myFundAdapter.FundListOtherClassAdapter;
import com.meixiang.adapter.myFundAdapter.FundListRecommendAdapter;
import com.meixiang.dialog.OptionalScreenPopup;
import com.meixiang.entity.fund.FundIndexResult;
import com.meixiang.entity.fund.FundInfoBean;
import com.meixiang.entity.fund.FundNewList;
import com.meixiang.global.Config;
import com.meixiang.http.HttpCallBack;
import com.meixiang.http.HttpUtils;
import com.meixiang.main.BaseFragment;
import com.meixiang.main.MXApplication;
import com.meixiang.recyclerview.OnItemClick;
import com.meixiang.tool.FundAnimationTool;
import com.meixiang.tool.Tool;
import com.meixiang.util.AbJsonUtil;
import com.meixiang.util.AbToastUtil;
import com.meixiang.util.DensityUtil;
import com.meixiang.view.swipetoloadlayout.base.OnLoadMoreListener;
import com.meixiang.view.swipetoloadlayout.base.OnRefreshListener;
import com.meixiang.view.swipetoloadlayout.base.SwipeToLoadLayout;

import org.json.JSONObject;

import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Response;

/**
 * 我的基金 -----产品数据
 */
public class FundListFragment extends BaseFragment implements View.OnClickListener, OptionalScreenPopup.IOnSubmitClickListener,
        OnRefreshListener, OnLoadMoreListener {

    @Bind(R.id.refresh)
    SwipeToLoadLayout mLoadLayout;
    @Bind(R.id.swipe_target)
    RecyclerView mRecyclerView;
    @Bind(R.id.rl_newest_price)
    RelativeLayout rl_newest_price; //最新价
    @Bind(R.id.tv_newest_price)
    TextView tv_newest_price;
    @Bind(R.id.iv_newest_price_sort)
    ImageView iv_newest_sort;  //对应图片
    @Bind(R.id.rl_amount_increase)
    RelativeLayout rl_amount_increase; //日涨幅
    @Bind(R.id.tv_day_price_amount_increase)
    TextView amount_increase;
    @Bind(R.id.iv_amount_increase_sort)
    ImageView iv_amount_increase_sort; //日涨幅对应图片
    @Bind(R.id.ll_optional_top_view)
    LinearLayout ll_optional_top_view;
    private FundListRecommendAdapter mRecommendAdapter;
    private FundListOtherClassAdapter mClassAdapter;
    private int index = 0;
    private OptionalScreenPopup mPopup;
    private View rootView;
    private float moveToCenter;
    private int clickNewestNum = 0; //记录净值单位点击的次数
    private int clickamountNum = 0; //记录日涨幅点击的次数
    private boolean isThree = false; //是否点击了 3次

    private int page = 1;
    private int pageSize = 10; //
    private int type = 0; //排序类型 0日涨幅，1近一周，2近一个月，3近三个月，4近六个月 5今年来 默认为：0
    private int rank_type = 0; // 排序 0默认排序，1从高到低，2从低到高 默认为：0
    private String rank_key_type = "0"; //净值排序 0默认排序，1从高到低，2从低到高 默认为：0
    private int channel_id; //频道ID
    private boolean isLoadMore = false;

    private List<FundInfoBean> fundInfoBeanList; // 其他
    private List<FundIndexResult.FundSiftBean> fundSiftBeanList; //精品推荐
    private String fund_id;
    private String titleName ;
    private Context context;
    private boolean is_first = true;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.activity_fund_list_fragment, container, false);
        ButterKnife.bind(this, rootView);
        super.onCreateView(inflater, container, savedInstanceState);
        index = getArguments().getInt("index");
        context = getActivity();
        return rootView;
    }

    @Override
    protected void initTitle() {

    }

    /**
     * 精品推荐数据
     */
    private void initRecommendData() {
        mRecommendAdapter = new FundListRecommendAdapter(getContext());
        mRecyclerView.setAdapter(mRecommendAdapter);
        LinearLayoutManager mLayoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecommendAdapter.setOnItemClickListener(new OnItemClick() {
            @Override
            public void onItemClick(View view, int position) {
                fund_id = fundSiftBeanList.get(position).getFund_id();
                titleName = fundSiftBeanList.get(position).getFund_name();
                toWebView();
            }
        });
    }

    /**
     * 获取除精品推荐除外的频道数据
     */
    private void getHttpFundNewListData() {
        HttpParams httpParams = new HttpParams();
        if(!"".equals(MXApplication.mApp.getUser().getMemberMobile())){
            httpParams.put("phone", MXApplication.mApp.getUser().getMemberMobile());
        }else{
            httpParams.put("phone", "");
        }
        httpParams.put("channel_id", String.valueOf(channel_id));
        httpParams.put("type", String.valueOf(type));
        httpParams.put("rank_type", String.valueOf(rank_type));
        httpParams.put("rank_key_type", rank_key_type);
        httpParams.put("page", String.valueOf(page));
        httpParams.put("pageSize", String.valueOf(pageSize));
        HttpUtils.post(Config.FUND_NEW_LIST, MyFundActivity.TAG, httpParams, new HttpCallBack(getActivity()) {
            @Override
            public void onSucceed(JSONObject result, String code, String message) {
                FundNewList fundNewList = AbJsonUtil.fromJson(result.optString("data").toString(), new TypeToken<FundNewList>() {
                });
                if (fundNewList.getFund_info().size() != 0) {
                    removeStatus();
                    if (isLoadMore) {
                        fundInfoBeanList.addAll(fundNewList.getFund_info());
                        mClassAdapter.refreshData(fundInfoBeanList);
                    } else {
                        fundInfoBeanList = fundNewList.getFund_info();
                        mClassAdapter.refreshData(fundInfoBeanList);
                    }
                } else {
                    if (is_first) {
                        showNoData("暂无数据");
                    }else{
                        AbToastUtil.showToast(getContext(), "暂无更多数据");
                    }
                }
            }

            @Override
            public void onError(String code, String message) {
                mLoadLayout.setRefreshing(false);
                mLoadLayout.setLoadingMore(false);
                showNoData(message, "重新加载", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        showLoading();
                        getHttpFundNewListData();
                    }
                });
            }
            @Override
            public void onAfter(boolean isFromCache, JSONObject jsonObject, Call call, Response response, Exception e) {
                super.onAfter(isFromCache, jsonObject, call, response, e);
                onComplete(mLoadLayout);
            }
        });
    }


    /**
     * 获取精品推荐频道数据
     */
    private void getHttpFundIndexData() {
        HttpUtils.post(Config.FUND_INDEX, MyFundActivity.TAG, null, new HttpCallBack(getActivity()) {
            @Override
            public void onSucceed(JSONObject result, String code, String message) {
                FundIndexResult fundIndexResult = AbJsonUtil.fromJson(result.optString("data").toString(), new TypeToken<FundIndexResult>() {
                });
                if (fundIndexResult != null && fundIndexResult.getFund_sift() != null) {
                    removeStatus();
                    fundSiftBeanList = fundIndexResult.getFund_sift();
                    mRecommendAdapter.refreshData(fundSiftBeanList);
                } else {
                    showNoData("暂无数据");
                }
                ll_optional_top_view.setVisibility(View.GONE);
                rl_amount_increase.setVisibility(View.GONE);
            }

            @Override
            public void onError(String code, String message) {
                ll_optional_top_view.setVisibility(View.GONE);
                rl_amount_increase.setVisibility(View.GONE);
                showNoData(message, "重新加载", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        showLoading();
                        getHttpFundIndexData();
                    }
                });
            }

            @Override
            public void onAfter(boolean isFromCache, JSONObject jsonObject, Call call, Response response, Exception e) {
                super.onAfter(isFromCache, jsonObject, call, response, e);
                onComplete(mLoadLayout);
            }
        });
    }

    /**
     * 其他频道数据
     */
    private void initOtherData() {
        ll_optional_top_view.setVisibility(View.VISIBLE);
        rl_amount_increase.setVisibility(View.VISIBLE);
        mClassAdapter = new FundListOtherClassAdapter(getContext());
        mRecyclerView.setAdapter(mClassAdapter);
        LinearLayoutManager mLayoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        //RecyclerView滑到底部自动加载更多
        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    if (!ViewCompat.canScrollVertically(recyclerView, 1)) {
                        mLoadLayout.setLoadingMore(true);
                    }
                }
            }
        });

        mClassAdapter.setOnItemClickListener(new OnItemClick() {
            @Override
            public void onItemClick(View view, int position) {
                fund_id = fundInfoBeanList.get(position).getFund_id();
                titleName = fundInfoBeanList.get(position).getFund_name() ;
                toWebView();
            }
        });
    }

    /**
     * 跳转到基金详情页 基金详情页
     */
    private void toWebView() {
        /**
         * 如果fundSessionId 不等于空 跳转到基金详情页
         * 反之则跳转到口袋登录
         */
        if (TextUtils.isEmpty(MXApplication.mApp.getSession().get("fundSessionId"))) {
            getHttpToLogin();
        } else {
            Intent intent = new Intent(context, WebviewActivity.class);
            intent.putExtra("url", Config.FUND_INFO_NEW + "?fund_id=" + fund_id);
            intent.putExtra("title", "基金详情");
            startActivity(intent);
        }
    }

    /***
     * toLogin 跳转登录或者注册界面API
     * url 回调地址
     */
    private void getHttpToLogin() {
        HttpParams params = new HttpParams();
        params.put("url", Config.CALLBACK_URL);
        HttpUtils.post(Config.FUND_TOLOGIN, MyFundActivity.TAG, params, new HttpCallBack(getActivity()) {
            @Override
            public void onSucceed(JSONObject result, String code, String message) { //成功则加载webView
                Intent intent = new Intent(context, WebviewActivity.class);
                intent.putExtra("url", result.optString("url"));
                intent.putExtra("title", "口袋登录");
                startActivity(intent);
            }

            @Override
            public void onError(String code, String message) {

            }
        });
    }

    /**
     * 主要为了获取fundSessionId ;获取成功则重新访问我的基金接口
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        toWebView();
    }

    @Override
    protected void initView() {
        FundAnimationTool.initAnimation();
        this.moveToCenter = (1.0F * (Tool.getWindowWith(getContext()) / 2 - this.rl_amount_increase.getMeasuredWidth() / 2 - DensityUtil.dip2px(getActivity(), 50.0F)) / Tool.getWindowWith(getContext()));
        rl_newest_price.setOnClickListener(this);
        rl_amount_increase.setOnClickListener(this);
    }

    @Override
    protected void setData() {
        showLoading();
        if (index == 0) { // index = 0 表示精品推荐
            channel_id = 0;
            getHttpFundIndexData();
            initRecommendData();
            mLoadLayout.setOnRefreshListener(this);
            mLoadLayout.setLoadMoreEnabled(false); //取消上拉加载更多操作
            return;
        } else {
            channel_id = index + 1;
            initOtherData();
            if (channel_id == 3) { //表示货币型频道
                tv_newest_price.setText("万分收益");
                amount_increase.setText("近七年化");
            }
            mLoadLayout.setLoadMoreEnabled(true);
            mLoadLayout.setOnRefreshListener(this);
            mLoadLayout.setOnLoadMoreListener(this);
            getHttpFundNewListData();
        }
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.rl_amount_increase: //日涨幅
                if (channel_id == 3) { //切换货币型频道则不显示筛选Popup
                    clickamountNum++;
                    if (!isThree) {
                        changeBgImage(clickamountNum, iv_amount_increase_sort);
                    }
                } else {
                    showSortPopupWindow(); //展示弹出筛选层
                }
                is_first = false ;
                getHttpFundNewListData();
                break;

            case R.id.rl_newest_price: //单位净值
                clickNewestNum++;
                if (!isThree) { //是否点击3次
                    changeBgImage(clickNewestNum, iv_newest_sort);
                }
                is_first = false ;
                getHttpFundNewListData();
                break;
        }
    }

    /**
     * 更改上下图标样式
     */
    private void changeBgImage(int number, ImageView imageView) {
        switch (number) {
            case 1:
                rank_key_type = "1";
                imageView.setImageResource(R.mipmap.sort1);
                break;
            case 2:
                imageView.setImageResource(R.mipmap.sort2);
                rank_key_type = "2";
                break;
            case 3:
                imageView.setImageResource(R.mipmap.sort3);
                rank_key_type = "0";
                clickNewestNum = 0;
                clickamountNum = 0;
                break;
        }
    }

    /**
     * 展示层的动画和左右移动的动画
     */
    protected void showSortPopupWindow() {
        if (this.mPopup == null)
            initPupopWindow();
        this.mPopup.setOutDissmissListener(new PopupWindow.OnDismissListener() {
            public void onDismiss() {
                FundListFragment.this.ll_optional_top_view.startAnimation(FundAnimationTool.left_disAnimation);
                FundListFragment.this.rl_amount_increase.startAnimation(FundAnimationTool.right_disAnimation);
                changeBgImage(rank_type, iv_amount_increase_sort);
            }
        });
        FundAnimationTool.initAniMation(moveToCenter);
        this.mPopup.startShowAnimation();
        this.mPopup.showAsDropDown(this.ll_optional_top_view); //设置显示的位置
        this.mPopup.setSubmitClickListener(this); //设置回调方法
        this.ll_optional_top_view.startAnimation(FundAnimationTool.left_showAnimation);
        this.rl_amount_increase.startAnimation(FundAnimationTool.right_showAnimation);
        FundAnimationTool.right_showAnimation.setFillAfter(true);
        FundAnimationTool.left_showAnimation.setFillAfter(true);
    }

    /**
     * 初始化Popup层
     */
    private void initPupopWindow() {
        View view = LayoutInflater.from(getContext()).inflate(R.layout.dialog_optional_screen_view, null);
        mPopup = new OptionalScreenPopup(getContext(), view, rootView.getLayoutParams().height);
    }

    /**
     * 点击Popup 页面的提交时，返回过来的参数
     *
     * @param selectPos //选择的条目
     * @param rank_type // 选择的净值收益
     * @param titleName // 选择条目的名称
     */
    @Override
    public void onClick(int selectPos, int rank_type, String titleName) {
        this.type = selectPos;
        this.rank_type = rank_type;
        amount_increase.setText(titleName);
        is_first = false ;
        getHttpFundNewListData();
    }

    /**
     * 加载更多
     */
    @Override
    public void onLoadMore() {
        page++;
        isLoadMore = true;
        is_first = false ;
        getHttpFundNewListData();
    }

    /**
     * 刷新
     */
    @Override
    public void onRefresh() {
        page = 1;
        isLoadMore = false;
        is_first = false ;
        if (channel_id == 0) {
            getHttpFundIndexData();
        } else {
            getHttpFundNewListData();
        }
    }

    public FundListFragment getIntance(Bundle bundle) {
        FundListFragment fundListFragment = new FundListFragment();
        fundListFragment.setArguments(bundle);
        return fundListFragment;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }
}
